<template>
  <div class="monitor-tree">
    <el-row :gutter="12" class="heightMax">
      <!-- 左侧：监控点列表 -->
      <el-col :span="6" class="heightMax">
        <el-row class="heightMax">
          <el-col :span="24" class="left-card">
            <el-card shadow="hover" class="tree-card">
              <div slot="header">监控点</div>
              <el-input v-model="filterText" placeholder="搜索" size="mini" clearable style="margin-bottom:10px" />
              <!-- 关键：滚动容器 -->
              <div class="tree-scroll">
                <el-tree ref="tree" :data="treeData" :props="defaultProps" :filter-node-method="filterNode"
                  highlight-current default-expand-all @node-click="handleNodeClick" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="24" class="left-card" style="margin-top: 6px">
            <el-card shadow="hover" class="table-card">
              <div class="table-scroll">
                <el-table :data="tableData" border>
                  <el-table-column prop="time" label="时间" show-overflow-tooltip />
                  <el-table-column prop="type" label="异常数据类型" show-overflow-tooltip width="110" />
                  <el-table-column prop="detail" label="详情" show-overflow-tooltip />
                </el-table>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
      <!-- 右侧：视频 -->
      <el-col :span="18" class="heightMax">
        <el-card shadow="hover" class="card-right heightMax">
          <!--          <div slot="header">实时监控 - {{ currentTitle }}</div>-->
          <div class="video-warp">
            <video ref="video" controls autoplay muted style="width:100%;height:100%;background:#000"
              @error="onVideoError">
              您的浏览器不支持 video 标签
            </video>
            <div v-if="loadError" style="text-align:center;padding:20px;">
              <p style="color:#f56c6c;margin-bottom:10px;">视频加载失败，请检查地址或网络</p>
              <el-button type="primary" size="mini" @click="retry">重新加载</el-button>
            </div>
          </div>
          <!-- <div class="video-warp">
            <video ref="video" controls autoplay muted style="width:100%;height:100%;background:#000"
              @error="onVideoError">
              您的浏览器不支持 video 标签
            </video>
            <div v-if="loadError" style="text-align:center;padding:20px;">
              <p style="color:#f56c6c;margin-bottom:10px;">视频加载失败，请检查地址或网络</p>
              <el-button type="primary" size="mini" @click="retry">重新加载</el-button>
            </div>
          </div>
          <div class="video-warp">
            <video ref="video" controls autoplay muted style="width:100%;height:100%;background:#000"
              @error="onVideoError">
              您的浏览器不支持 video 标签
            </video>
            <div v-if="loadError" style="text-align:center;padding:20px;">
              <p style="color:#f56c6c;margin-bottom:10px;">视频加载失败，请检查地址或网络</p>
              <el-button type="primary" size="mini" @click="retry">重新加载</el-button>
            </div>
          </div>
          <div class="video-warp">
            <video ref="video" controls autoplay muted style="width:100%;height:100%;background:#000"
              @error="onVideoError">
              您的浏览器不支持 video 标签
            </video>
            <div v-if="loadError" style="text-align:center;padding:20px;">
              <p style="color:#f56c6c;margin-bottom:10px;">视频加载失败，请检查地址或网络</p>
              <el-button type="primary" size="mini" @click="retry">重新加载</el-button>
            </div>
          </div> -->
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Hls from 'hls.js'
import { areatree, alarmlist } from '@/api/home.js'
export default {
  name: 'MonitorTree',
  data() {
    return {
      filterText: '',
      currentTitle: '石场出入口',
      currentUrl: '',
      loadError: false,
      // ① 去掉失效地址，全部换成长期有效的 HLS 测试流
      treeData: [
        {
          label: 'VOF4石场',
          children: [
            { label: '石场出入口', url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8' },
            { label: '石场加工区', url: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8' },
            { label: '石场采场', url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8' },
            { label: '石场排土场', url: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8' }
          ]
        }
      ],
      defaultProps: { children: 'children', label: 'label' },
      hls: null,
      tableData: [],
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    areatree().then(res => {
      res.data.forEach(element => {
        element.label = element.areaName
        if (element.children) {
          element.children.forEach(item => {
            item.label = item.areaName
            // item.url = item.monitorUrl
            item.url = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'
          })
        }
      });
      console.log(res.data)
      this.treeData = res.data
      this.handleNodeClick(this.treeData[0].children[0])
    })

    alarmlist().then(res => {
      this.tableData = res.data
    })
  },
  beforeDestroy() {
    this.destroy()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      if (!data.url) return
      this.currentTitle = data.label
      this.currentUrl = data.url.trim()
      this.loadError = false
      this.playUrl(this.currentUrl)
    },
    playUrl(url) {
      this.destroy()
      const video = this.$refs.video
      if (!url) { this.onVideoError(); return }

      // ② HLS 流
      if (url.endsWith('.m3u8')) {
        if (Hls.isSupported()) {
          this.hls = new Hls({ debug: false })
          this.hls.loadSource(url)
          this.hls.attachMedia(video)
          this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
            // ③ 防止 play() 被旧实例打断
            video.play().catch(() => { })
          })
          this.hls.on(Hls.Events.ERROR, (e, data) => {
            if (data.fatal) this.onVideoError()
          })
        } else {
          video.src = url
        }
        return
      }

      // 普通 mp4/flv
      video.src = url
      video.play().catch(() => this.onVideoError())
    },
    onVideoError() {
      this.loadError = true
    },
    retry() {
      this.loadError = false
      this.playUrl(this.currentUrl)
    },
    destroy() {
      if (this.hls) {
        this.hls.destroy()
        this.hls = null
      }
      const v = this.$refs.video
      if (v) {
        v.pause()
        v.removeAttribute('src') // ④ 彻底断开
        v.load()
      }
    }
  }
}
</script>

<style scoped lang="scss">
/* 如果想让滚动条细一点（可选） */
.tree-scroll::-webkit-scrollbar {
  width: 6px;
}

.tree-scroll::-webkit-scrollbar-thumb {
  background: #dcdcdc;
  border-radius: 3px;
}

.monitor-tree {
  padding:16px;
  height: 100%;

  .left-card {
    height: 50%;
  }
}

.card-right {

  ::v-deep .el-card__body {
    padding: 0 !important;
    height: 100%;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    justify-content: flex-start;
  }
}

.left-card {
  ::v-deep .el-card__body {
    padding: 10px 5px !important;

  }

  ::v-deep .el-table__header {
    width: 100% !important;
  }
}

.heightMax {
  height: 100%;
}

.app-main {
  height: 100% !important;
}

.el-card {
  height: calc(100% - 6px);
}

.video-warp {
  width: 33.3%;
  height: 33.33%;
}

.tree-card {
  height: 100%;
  display: flex;
  flex-direction: column;

  ::v-deep .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden; // 关键
  }
}

.tree-scroll {
  flex: 1 1 auto;
  overflow-y: auto; // 纵向滚动
  min-height: 0; // 兼容 flex 子元素被撑开
}

.table-card {
  height: 100%;

  ::v-deep .el-card__body {
    height: 100%;
    padding: 0;
  }
}

.table-scroll {
  height: 100%;
  overflow-y: auto; // 纵向滚动
}
</style>
